package android.com.br.braziltvguide;

import java.util.*;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.Cursor;

public class Canais extends Activity{

    private String[] id;
    private String[] nome;
    private int[] flag;
    private SQLiteDatabase BDtvguide = null;
    private Boolean blnInicio = true;
    int contador = 0;
    private final List<String> selecionados = new ArrayList<String>();
    ArrayList<String> results = new ArrayList<String>();
    
    EditText busca;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.canais);
          
          busca = (EditText) findViewById(R.id.txtbusca);
          
          busca.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        	  public void onFocusChange(View arg0, boolean arg1) {
        		  	BuscaCanal(busca.getText().toString());
        	      }
        	    });
          
          BuscaCanal(null);
    
    }
    
    
    @Override
	protected void onStop() {
    	BDtvguide.close();
		finish();
		super.onStop();
	}
    
    private void BuscaCanal(String canal) {
    	
    try{
      
    	
      if(BDtvguide!= null)
    	  BDtvguide.close();
      
  	  BDtvguide =  this.openOrCreateDatabase("canais", MODE_PRIVATE, null);
  	  
  	  Cursor c;
  	  contador = 0;
  	
  	  if(canal==null)
  		  c = BDtvguide.rawQuery("SELECT ID, NOME, FLAG FROM canais ORDER BY NOME", null);
  	  else
  		  c = BDtvguide.rawQuery("SELECT ID, NOME, FLAG FROM canais WHERE NOME LIKE '" + canal +"%' ORDER BY NOME", null);
  	  
      	if (c != null ) {
      		if  (c.moveToFirst()) {
      			
   	    	    id = new String[c.getCount()];
   	    	    nome = new String[c.getCount()];
   	    	    flag = new int[c.getCount()];
   	    	    
      			do {
      				id[contador] = c.getString(c.getColumnIndex("ID"));
      				nome[contador] = c.getString(c.getColumnIndex("NOME"));
      				flag[contador] = c.getInt(c.getColumnIndex("FLAG"));
      				results.add(nome[contador]);
      				contador++;
      			}while (c.moveToNext());
      			
      			
      	        ListView lsvEstados = (ListView) findViewById(R.id.lsvCanais);

      	        ArrayAdapter<String> lsvCanaisAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1) {
      	            @Override
      	            public View getView(int position, View convertView, ViewGroup parent) {
      	                
      	            	String canais = nome[position];
      	            	String idcanais = id[position];
      	            	int flagcanais = flag[position];
      	            	
      	        		View v = convertView;

      	                if(v==null) {
      	                	LayoutInflater inflater = getLayoutInflater();
      	                	v = (View) inflater.inflate(R.layout.item_canais, null);
      	        	}

      	        	CheckBox chk = (CheckBox) v.findViewById(R.id.chkCanais);

      	        	chk.setTag(idcanais);
      	        	
      	        	if(flagcanais==1 && blnInicio)
      	        		selecionados.add(idcanais);
      	        	else if(flagcanais==0 && blnInicio)
      	        		selecionados.remove(idcanais);
      	        	
      	        	chk.setOnClickListener(new View.OnClickListener() {
      	        	    @Override
      	        	    public void onClick(View v) {
      	        	        CheckBox chk = (CheckBox) v;
      	        		String idcanais = (String) chk.getTag();
      	        		if(chk.isChecked()) {
      	        			
      	        			blnInicio = false;
      	        			
      	        			BDtvguide.execSQL("UPDATE canais SET FLAG = 1 WHERE ID = '" + idcanais + "'");
      	        			
      	        		    if(!selecionados.contains(idcanais))
      	        	                selecionados.add(idcanais);
      	        		} else {
      	        	            
      	        			    
      	        				blnInicio = false;
      	        				
      	        				BDtvguide.execSQL("UPDATE canais SET FLAG = 0 WHERE ID = '" + idcanais + "'");
      	        			    
      	        	            if(selecionados.contains(idcanais))
      	        	                selecionados.remove(idcanais);
      	        	        }
      	        	    }
      	        	});
      	        	
      	        	if(selecionados.contains(idcanais)) {
      	        	    chk.setChecked(true);
      	        	} else {
      	        	    chk.setChecked(false);
      	        	}

      	        	TextView txv = (TextView) v.findViewById(R.id.txvCanais);
      	        	txv.setText(canais);

      	        	return v;
      	            }

      	            @Override
      	            public long getItemId(int position) {
      	                return position;
      	            }

      	            @Override
      	            public int getCount() {
      	                return nome.length;
      	            }
      	        };
      	        lsvEstados.setAdapter(lsvCanaisAdapter);
      		} 
      	}
    } catch (SQLiteException e ) {
			AlertDialog.Builder msg4 = new AlertDialog.Builder(Canais.this);
			msg4.setTitle("Brazil TvGuide");
			msg4.setMessage("Erro ao acessar a base de dados, Motivo: " + e.getMessage());
			msg4.setNeutralButton("OK", null);
			msg4.show();
      }
}

}